package com.all.security.service.impl;

import com.all.security.model.entity.SysUser;
import com.all.security.mapper.SysUserMapper;
import com.all.security.model.entity.SysUserDetails;
import com.all.security.service.ISysUserRoleService;
import com.all.security.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-03-31
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private ISysUserRoleService iSysUserRoleService;

    @Override
    public SysUserDetails buildSysUserDetails(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, username)
                .eq(SysUser::getStatus, 0)
                .eq(SysUser::getDelFlag, 0);
        SysUser user = baseMapper.selectOne(wrapper);
        SysUserDetails details = null;
        if (user != null) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            List<String> permissionList = iSysUserRoleService.getSysUserPerms(user.getUserId());
            permissionList.stream().forEach(r -> authorities.add(new SimpleGrantedAuthority(r)));
            details = new SysUserDetails(user.getUserId(),
                    user.getUserName(),
                    user.getNickName(),
                    user.getPassword(),
                    authorities);
        }
        return details;
    }
}
